package com.mitou.common.utils.web;

import com.alibaba.fastjson.JSONObject;
import com.mitou.base.entity.BaseUser;
import com.mitou.common.constants.BaseConstants;
import com.mitou.common.exception.business.UserNotLoginException;
import org.springframework.data.redis.RedisConnectionFailureException;
import org.springframework.stereotype.Component;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.concurrent.TimeUnit;

/**
 * 系统上下文信息
 *
 * @author rice
 * @since 2021-03-25
 */
@Component
public class BaseContextUtil {

    @Resource
    private RedisCacheUtil redisCacheUtil;

    /**
     * 获取当前登录用户id
     *
     * @return
     */
    public Long getUserId() {
        try {
            return this.getLoginUser().getUserId();
        } catch (Exception e) {
            throw new UserNotLoginException();
        }
    }

    /**
     * 获取当前登录用户
     *
     * @return
     */
    public BaseUser getLoginUser() {
        return getLoginUser(RequestContextUtil.getRequest().getHeader(BaseConstants.TOKEN_MAME));
    }

    /**
     * 获取当前登录用户
     *
     * @return
     */
    public BaseUser getLoginUser(String token) {
        String userStr;
        try {
            userStr = redisCacheUtil.getStr(token);
        } catch (RedisConnectionFailureException e) {
            throw new RedisConnectionFailureException("redis数据库连接异常！");
        }
        if (null == userStr) {
            throw new UserNotLoginException();
        }
        return JSONObject.parseObject(userStr, BaseUser.class);
    }

    /**
     * 生成token
     *
     * @param one 用户信息
     * @return
     */
    public String generateToken(BaseUser one) {
        try {
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            //定义加密值
            String salt = one.getLoginName() + System.currentTimeMillis();
            //加密生成token
            return Base64Utils.encodeToString(
                    md5.digest(salt.getBytes(StandardCharsets.UTF_8))
            );
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("服务器加密失败，请稍后重试！");
        }
    }

    /**
     * 清除当前登录用户token
     *
     * @return
     */
    public boolean removeToken() {
        boolean bool = false;
        try {
            String token = RequestContextUtil.getRequest().getHeader(BaseConstants.TOKEN_MAME);
            bool = redisCacheUtil.deleteStr(token);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return bool;
    }

    /**
     * 为token续期
     *
     * @return
     */
    public void renewalToken(String token) {
        if (!StringUtils.isEmpty(token)) {
            redisCacheUtil.expire(token, BaseConstants.TOKEN_DURATION_TIME, TimeUnit.HOURS);
        }
    }
}
